<template>
  <div class="view-container">
    <el-form :model="queryParam" label-width="auto">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="queryParam.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="角色字符" prop="roleKey">
            <el-input v-model="queryParam.roleKey" placeholder="请输入角色字符"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetParams">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <nebula-table :data="tableData" :columns="columns" header-row-class-name="header-row-class" size="default" border
                  :total="rowsTotal" :default-page-size="10" show-overflow-tooltip use-tool-bar @change="changePage">
      <template #head-toolbar>
        <el-button type="primary" @click="handleCreate" size="small" v-permission="'role.add'">新增</el-button>
      </template>
      <template #roleName="scope">
        <router-link :to=genDetailUrl(scope.row) class="table-link">
          {{ scope.row.roleName }}
        </router-link>
      </template>
      <template #roleStatus="scope">
        <el-switch v-model="scope.row.roleStatus" :active-value="0" :inactive-value="1" active-text="正常"
                   inactive-text="停用" @change="switchChange(scope)" inline-prompt></el-switch>
      </template>
      <template #operation="scope">
        <el-button size="small" @click="authorization(scope.row)">授权管理</el-button>
        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </nebula-table>

    <el-dialog v-model="isShow" title="新增角色">
      <div class="view-container">
        <el-form :model="createParam" label-width="auto">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="createParam.roleName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色字符" prop="roleKey">
                <el-input v-model="createParam.roleKey"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="orderNo">
                <el-input-number v-model="createParam.orderNo" :min="0"
                                 class="width-control"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="createParam.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="createCancel">取消</el-button>
        <el-button type="primary" @click="createSubmit">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showAuth" title="授权管理">
      <div class="view-container">
        <el-tree
            :data="menuData"
            :showCheckbox="true"
            v-model:checkedKeys="checkedKeys"
            :replaceFields="replaceFields"
            :default-expand-all="true"
        >
        </el-tree>
      </div>
      <template #footer>
        <el-button @click="authCancel">取消</el-button>
        <el-button type="primary" @click="authSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {commitAuth, createOrUpdateSysRole, getRoleList, getRoleMenuList} from "@/api/sysRole.js";
import {getMenuList} from "@/api/sysMenu.js";
import NebulaTable from "@/components/NebulaTable.vue";
import {ElMessageBox, ElNotification} from "element-plus";

defineOptions({
  name: 'sysRole'
})

const queryParam = ref({
  roleName: null,
  roleKey: null,
  pageNum: 1,
  pageSize: 10
})

const rowsTotal = ref(0)
const tableData = ref([])

const page = reactive({
  current: queryParam.value.pageNum,
  limit: queryParam.value.pageSize,
  total: rowsTotal,
  layout: ["prev", "page", "next", "limits", "count"],
});

const columns = [
  {title: "角色名称", key: "roleName", customSlot: "roleName", align: "center"},
  {title: "角色字符", key: "roleKey", align: 'center'},
  {title: "排序", key: "orderNo", align: 'center'},
  {title: "角色状态", key: "roleStatus", align: 'center', customSlot: "roleStatus"},
  {title: "创建时间", key: "createTime", align: 'center'},
  {title: "操作", align: 'center', customSlot: 'operation'}
]

const isShow = ref(false)

const createParam = ref({
  roleName: null,
  roleKey: null,
  orderNo: 1,
  remark: null
})

const createCancel = () => {
  isShow.value = false
  for (let key in createParam.value) {
    if (key === "orderNo") {
      createParam.value[key] = 1
    } else {
      createParam.value[key] = null;
    }
  }
}

const createSubmit = () => {
  createOrUpdateSysRole(createParam.value).then(res => {
    if (res.code === 200) {
      isShow.value = false
      handleQuery()
      ElNotification({
        title: "操作成功",
        type: "success"
      })
    } else {
      ElNotification({
        title: "创建失败",
        message: res.msg,
        type: "error"
      })
    }
  })
}

const showAuth = ref(false)
const currentRoleId = ref()
const replaceFields = ref({
  id: 'id',
  title: "menuTitle",
  children: "sysMenuList"

})

const checkedKeys = ref([])

const menuData = ref([])

const authCancel = () => {
  showAuth.value = false
}

const authSubmit = () => {
  let param = {
    roleId: currentRoleId.value,
    newMenuIdList: checkedKeys.value
  }
  commitAuth(param).then(res => {
    if (res.code === 200) {
      showAuth.value = false
      ElNotification({
        title: "操作成功",
        type: "success"
      })
    } else {
      ElNotification({
        title: "创建失败",
        message: res.msg,
        type: "error"
      })
    }
  })
}

const genDetailUrl = (row) => {
  return "/system/role/detail/" + row.id;
}


const handleQuery = () => {
  getRoleList(queryParam.value).then(res => {
    tableData.value = res.data.rows
    rowsTotal.value = res.data.total
  })
}

const resetParams = () => {
  for (let key in queryParam.value) {
    if (key !== "pageNum" && key !== "pageSize") {
      queryParam.value[key] = null;
    }
  }
}

const changePage = (currentPage,pageSize) => {
  queryParam.value.pageNum = currentPage
  queryParam.value.pageSize = pageSize
  handleQuery()
}

const handleCreate = () => {
  isShow.value = true
}

const handleEdit = (row) => {
  createParam.value = {...row}
  isShow.value = true
}

const switchChange = (scope) => {
  const row = scope.row
  const index = scope.index
  if (index === -1) return
  const changeParam = {
    id: row.id,
    roleStatus: row.roleStatus
  }
  createOrUpdateSysRole(changeParam).then(res => {
    if (res.code === 200) {
      handleQuery()
      ElNotification({
        title: "操作成功",
        type: "success"
      })
    } else {
      ElNotification({
        title: "创建失败",
        message: res.msg,
        type: "error"
      })
    }
  })
}

const handleDelete = (row) => {
  const confirmText = `确定要删除角色【${row.roleName}】吗?`
  ElMessageBox.confirm(
      confirmText,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    const changeParam = {
      id: row.id,
      isDeleted: 1
    }
    createOrUpdateSysRole(changeParam).then(res => {
      if (res.code === 200) {
        handleQuery()
        ElNotification({
          title: "操作成功",
          type: "success"
        })
      } else {
        ElNotification({
          title: "操作失败",
          message: res.msg,
          type: "error"
        })
      }
    })
  })
}

const authorization = (row) => {
  getMenuData();
  const roleMenuParam = {
    roleId: row.id
  }
  getRoleMenuList(roleMenuParam).then(res => {
    checkedKeys.value = res.data
    showAuth.value = true
  })
  currentRoleId.value = row.id

}

const getMenuData = () => {
  let typeList = [1, 2, 3]
  let param = {
    typeList: typeList.join(',')
  }
  getMenuList(param).then(res => {
    menuData.value = res.data
  })
}


onMounted(() => {
  handleQuery()
})


</script>
